import { defineStore } from 'pinia'
import { Cache } from "@/storage"
import { CacheKey } from "@/storage/mutation-type"
import { http } from "@/service"

const InitUserInfo = {
  uid: 0,
  nickname: '',
  avatar: '',
}
interface LoginData {
  username: string
  password: string
}
interface UserState {
  uid?: number
  name?: string
  avatar?: string
}
export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserState>({ ...InitUserInfo })

  // Set user's information
  const setInfo = (partial: Partial<UserState>) => {
    userInfo.value = { ...partial }
  }

  const login = async (loginForm: LoginData) => {
    try {
      const { data } = await http.post('login', loginForm)
      Cache.setLocal(CacheKey.TOKEN, data)
    }
    catch (error) {
      Cache.removeLocal(CacheKey.TOKEN)
      throw error
    }
  }

  const logout = async () => {
    try {
      await http.post('logout')
    }
    finally {
      Cache.removeLocal(CacheKey.TOKEN)
      setInfo({ ...InitUserInfo })
    }
  }


  return {
    userInfo,
    login,
    logout,
  }
})

export default useUserStore
